const bcrypt = require('bcryptjs')
const { getUserInfo } = require('../service/user.service')
const {
    useraFormateError,
    userAlreadyExited,
    userDoesNotExist,
    userLoginError,
    userInvalidPassword
} = require('../constant/err.type')

const userValidator = async (ctx, next) => {
    // 1.获取数据
    const { user_name, password } = ctx.request.body
    // 合法性
    if (!user_name || !password) {
        ctx.app.emit('error', useraFormateError, ctx)
        return
    }
    await next()
}

const verifyUser = async (ctx, next) => {
    // 1.获取数据
    const { user_name } = ctx.request.body
    // 合理性
    try {
        const res = await getUserInfo({ user_name })
        if (res) {
            ctx.app.emit('error', userAlreadyExited, ctx)
            return
        }
    } catch (error) {
        // 获取用户信息错误
        ctx.app.emit('error', userRegisterError, ctx)
        return
    }
    await next()
}

// 密码加密
const cryptPassword = async (ctx, next) => {
    const { password } = ctx.request.body
    const salt = bcrypt.genSaltSync(10)
    const hash = bcrypt.hashSync(password, salt)

    ctx.request.body.password = hash

    await next()
}

const verifyLogin = async (ctx, next) => {
    // 1.判断用户是否存在（不存在：报错）
    const { user_name, password } = ctx.request.body
    try {
        const res = await getUserInfo({ user_name })
        if (!res) {
            ctx.app.emit('error', userDoesNotExist, ctx)
            return
        }

        // 2.密码是否匹配（不匹配：报错）
        if (!bcrypt.compareSync(password, res.password)) {
            ctx.app.emit('error', userInvalidPassword, ctx)
            return
        }

    } catch (err) {
        console.error(err)
        return ctx.app.emit('error', userLoginError, ctx)
    }

    await next()
}

module.exports = {
    userValidator,
    verifyUser,
    cryptPassword,
    verifyLogin
}